/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kungkhies.desktop.activity.importer.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.swing.JFileChooser;

import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.Exceptions;
import org.openide.cookies.SaveCookie;

import com.kungkhies.desktop.activity.explorer.ActivityExplorerTopComponent;
import com.kungkhies.desktop.library.entities.Activity;
import java.util.ArrayList;
import java.util.List;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor.Confirmation;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//com.kungkhies.desktop.activity.importer.ui//ActivityImporterUI//EN",
autostore = false)
@TopComponent.Description(preferredID = "ActivityImporterUITopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "com.kungkhies.desktop.activity.importer.ui.ActivityImporterUITopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_ActivityImporterUIAction",
preferredID = "ActivityImporterUITopComponent")
public final class ActivityImporterUITopComponent extends TopComponent
{
    private int returnVal;
    private JFileChooser jFileChooser1;
    private SaveCookieImpl impl;

    public ActivityImporterUITopComponent()
    {
        initComponents();
        setName(NbBundle.getMessage(ActivityImporterUITopComponent.class, "CTL_ActivityImporterUITopComponent"));
        setToolTipText(NbBundle.getMessage(ActivityImporterUITopComponent.class, "HINT_ActivityImporterUITopComponent"));

        jFileChooser1 = new JFileChooser();
        contentsTextArea.setEditable(false);

        ActionListener actionListener = new ActionListener()
        {
            public void actionPerformed(ActionEvent actionEvent)
            {
                jFileChooser1 = (JFileChooser) actionEvent.getSource();
                String command = actionEvent.getActionCommand();
                if (command.equals(JFileChooser.APPROVE_SELECTION))
                {
                    File selectedFile = jFileChooser1.getSelectedFile();
                    System.out.println(selectedFile.getParent());
                    selectedFileTextField.setText(selectedFile.getName());
                    contentsTextArea.setText("");
                    readFileIntoTextArea(selectedFile);
                }
                else if (command.equals(JFileChooser.CANCEL_SELECTION))
                {
                    System.out.println(JFileChooser.CANCEL_SELECTION);
                }
            }
        };

        jFileChooser1.addActionListener(actionListener);
        
        impl = new SaveCookieImpl();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fileLabel = new javax.swing.JLabel();
        selectedFileTextField = new javax.swing.JTextField();
        javax.swing.JLabel descriptionLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        contentsTextArea = new javax.swing.JTextArea();
        activityTitleLabel = new javax.swing.JLabel();
        chooseFileButton = new javax.swing.JButton();
        importActivitiesButton = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        org.openide.awt.Mnemonics.setLocalizedText(fileLabel, org.openide.util.NbBundle.getMessage(ActivityImporterUITopComponent.class, "ActivityImporterUITopComponent.fileLabel.text")); // NOI18N

        selectedFileTextField.setText(org.openide.util.NbBundle.getMessage(ActivityImporterUITopComponent.class, "ActivityImporterUITopComponent.selectedFileTextField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(descriptionLabel, org.openide.util.NbBundle.getMessage(ActivityImporterUITopComponent.class, "ActivityImporterUITopComponent.descriptionLabel.text")); // NOI18N

        contentsTextArea.setColumns(20);
        contentsTextArea.setRows(5);
        jScrollPane1.setViewportView(contentsTextArea);

        activityTitleLabel.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(activityTitleLabel, org.openide.util.NbBundle.getMessage(ActivityImporterUITopComponent.class, "ActivityImporterUITopComponent.activityTitleLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(chooseFileButton, org.openide.util.NbBundle.getMessage(ActivityImporterUITopComponent.class, "ActivityImporterUITopComponent.chooseFileButton.text")); // NOI18N
        chooseFileButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                chooseFileButtonMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(importActivitiesButton, org.openide.util.NbBundle.getMessage(ActivityImporterUITopComponent.class, "ActivityImporterUITopComponent.importActivitiesButton.text")); // NOI18N
        importActivitiesButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                importActivitiesButtonMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jButton3, org.openide.util.NbBundle.getMessage(ActivityImporterUITopComponent.class, "ActivityImporterUITopComponent.jButton3.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(64, 64, 64)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(importActivitiesButton)
                        .addGap(18, 18, 18)
                        .addComponent(jButton3))
                    .addComponent(chooseFileButton)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(selectedFileTextField, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(descriptionLabel, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 623, Short.MAX_VALUE)
                        .addComponent(activityTitleLabel, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(fileLabel, javax.swing.GroupLayout.Alignment.LEADING)))
                .addContainerGap(88, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addComponent(activityTitleLabel)
                .addGap(43, 43, 43)
                .addComponent(fileLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(selectedFileTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(chooseFileButton)
                .addGap(41, 41, 41)
                .addComponent(descriptionLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(importActivitiesButton)
                    .addComponent(jButton3))
                .addContainerGap(219, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void chooseFileButtonMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_chooseFileButtonMouseClicked
    {//GEN-HEADEREND:event_chooseFileButtonMouseClicked
        returnVal = jFileChooser1.showOpenDialog(this);        // TODO add your handling code here:
    }//GEN-LAST:event_chooseFileButtonMouseClicked

    private void importActivitiesButtonMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_importActivitiesButtonMouseClicked
    {//GEN-HEADEREND:event_importActivitiesButtonMouseClicked
        try
        {
            impl.save();
        }
        catch (IOException ex)
        {
            Exceptions.printStackTrace(ex);
        }
        
        ActivityExplorerTopComponent.refreshNode();
        
                
    }//GEN-LAST:event_importActivitiesButtonMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel activityTitleLabel;
    private javax.swing.JButton chooseFileButton;
    private javax.swing.JTextArea contentsTextArea;
    private javax.swing.JLabel fileLabel;
    private javax.swing.JButton importActivitiesButton;
    private javax.swing.JButton jButton3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField selectedFileTextField;
    // End of variables declaration//GEN-END:variables

    @Override
    public void componentOpened()
    {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed()
    {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p)
    {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p)
    {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    public void readFileIntoTextArea(File selectedFile)
    {
        FileObject fileObject = FileUtil.toFileObject(FileUtil.normalizeFile(selectedFile));

        try
        {
            InputStream is = fileObject.getInputStream();

            InputStreamReader reader = new InputStreamReader(is);

            BufferedReader buf = new BufferedReader(reader);

            String line;
            try
            {
                while ((line = buf.readLine()) != null)
                {
                    contentsTextArea.append(line + "\n");
                }
            }
            catch (IOException ex)
            {
                Exceptions.printStackTrace(ex);
            }

        }
        catch (FileNotFoundException ex)
        {
            Exceptions.printStackTrace(ex);
        }
    }

    private class SaveCookieImpl implements SaveCookie
    {
        @Override
        public void save() throws IOException
        {
            Confirmation message = new NotifyDescriptor.Confirmation("Do you want to save?",
                    NotifyDescriptor.OK_CANCEL_OPTION,
                    NotifyDescriptor.QUESTION_MESSAGE);
            Object result = DialogDisplayer.getDefault().notify(message);
            //When user clicks "Yes", indicating they really want to save,
            //we need to disable the Save action,
            //so that it will only be usable when the next change is made
            //to the JTextArea:


            if (NotifyDescriptor.YES_OPTION.equals(result))
            {
                List<Activity> activityList = getActivityList();
                EntityManager entityManager = Persistence.createEntityManagerFactory("KungkhieEntityLibraryPU").createEntityManager();
                entityManager.getTransaction().begin();

                for (Activity ac : activityList)
                {
                    entityManager.persist(ac);
                }
                
                entityManager.getTransaction().commit();
            }
        }
    }

    public List<Activity> getActivityList()
    {
        File selectedFile = jFileChooser1.getSelectedFile();
        FileObject fileObject = FileUtil.toFileObject(FileUtil.normalizeFile(selectedFile));

        List<Activity> activityList = new ArrayList<Activity>();

        try
        {
            InputStream is = fileObject.getInputStream();

            InputStreamReader reader = new InputStreamReader(is);

            BufferedReader buf = new BufferedReader(reader);

            String line;
            try
            {
                while ((line = buf.readLine()) != null)
                {
                    Activity activity = processCsvString(line);
                    if (activity == null)
                    {
                        continue;
                    }
                    activityList.add(activity);
                }
            }
            catch (IOException ex)
            {
                Exceptions.printStackTrace(ex);
            }



        }
        catch (FileNotFoundException ex)
        {
            Exceptions.printStackTrace(ex);
        }

        return activityList;
    }

    private Activity processCsvString(String line)
    {
        String[] activityValues = line.split("\\^");
        
        System.out.println("Entities in line.split[;]: " + activityValues.length);

        if (activityValues.length != 5)
        {
            return null;
        }

        Activity activityImport = new Activity();

        activityImport.setName(activityValues[0]);
        activityImport.setDescription(activityValues[1]);
        activityImport.setAssessment(activityValues[2]);
        activityImport.setUrl(activityValues[3]);

        return activityImport;

    }
}
